package com.ttloner1.preparedstatement;

import com.ttloner1.bean.ExamStudent;
import com.ttloner1.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

/**
 * @author TTLoner
 * @date 2021/6/21 21:10
 * @description
 * 针对表ExamStudent的
 */
public class ESQuery {
    public ArrayList<ExamStudent> Select(String sql, String[] args){
        //返回的结果集
        ArrayList<ExamStudent> result = new ArrayList<>();
        //连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            //预编译
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            //获取结果
            rs = ps.executeQuery();
            //获取元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int count = metaData.getColumnCount();
            Class clazz = Class.forName("com.ttloner1.bean.ExamStudent");
            while(rs.next()){
                ExamStudent ES = new ExamStudent();
                for(int i=0;i<count;i++){
                    //获取列的列名，不推荐使用
                    String CName = metaData.getColumnName(i+1);
                    //获取列的别名：getColumnLabel
                    //通过反射获取
                    Field field = clazz.getDeclaredField(CName);
                    System.out.println(field);
                    field.setAccessible(true);
                    System.out.println(rs.getObject(i + 1).getClass());
                    System.out.println(rs.getObject((i + 1)));
                    field.set(ES, rs.getObject(i+1));
                }
                result.add(ES);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            //关闭流
            JDBCUtils.closeConnection(conn,ps,rs);
        }
        return result;
    }
    @Test
    public void test(){
        //永远不要用通配符去替换字段，自动转string
//        String sql="select ?,?,? from examstudent";
//        String[] args={"`Location`","`IDCard`","`StudentName`"};
        String sql="select * from examstudent";
        String[] args={};
        ArrayList<ExamStudent> select = Select(sql, args);
        System.out.println(select);
    }
}
